<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>编辑结构</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/layui/css/layui.css}"/>
</head>
<body>
<form class="layui-form" method="POST" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">中文名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" maxlength="20" autocomplete="off"
                           placeholder="请输入结构中文名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">英文名称</label>
                <div class="layui-input-block">
                    <input type="text" name="nameEn" maxlength="50"
                           placeholder="请输入结构英文名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">排序值</label>
                <div class="layui-input-block">
                    <input name="sort" maxlength="5" placeholder="请输入排序值"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">结构项</label>
                <div class="struct">
                    <!-- 动态生成的结构项将被添加到这里 -->
                </div>
            </div>
            <!-- 添加按钮放在表单内部 -->
            <div class="layui-form-item">
                <div class="layui-input-block" style="float: right;margin-right: 10px">
                    <button type="button" class="layui-btn layui-btn-sm" lay-event="add">
                        <i class="layui-icon layui-icon-add-1"></i> 添加结构项
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-success layui-btn-sm" lay-submit=""
                    lay-filter="struct-edit">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>
<script type="text/html" id="structTemplate">
    <div class="layui-input-block cloned-struct-item" id="structContainer"
         style="border: 1px solid #ededed; margin-right: 20px;margin-bottom: 10px">
        <button class="layui-btn layui-btn-sm" lay-event="remove" style="margin-right: 0;float: right">
            <i class="layui-icon layui-icon-delete"></i>
        </button>
        <div class="layui-form-item">
            <label class="layui-form-label">中文名称</label>
            <div class="layui-input-block">
                <input type="text" name="names[0]" maxlength="20"
                       autocomplete="off"
                       placeholder="请输入结构中文名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">英文名称</label>
            <div class="layui-input-block">
                <input type="text" name="nameEns[0]" maxlength="50"
                       placeholder="请输入结构英文名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">文本类型</label>
            <div class="layui-input-block">
                <select name="typeId[0]" class="layui-select struct-type-select" lay-filter="struct-type-select">
                    <option value="">请选择文本类型</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序值</label>
            <div class="layui-input-block">
                <input name="sorts[0]" maxlength="5" placeholder="请输入排序值"
                       class="layui-input">
            </div>
        </div>
    </div>
</script>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:inline="javascript">
    layui.use(['form', 'jquery', 'layer'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let layer = layui.layer; // 确保引入 layer 模块
        let baseURL = /*[[@{/}]]*/ '';
        const container = $('.struct');
        // 添加按钮点击事件
        $('button[lay-event="add"]').on('click', function (event) {
            event.preventDefault();
            // 获取外部盒子
            let templateContent = $('#structTemplate').html(); // 提取模板内容
            let newStructItem = $(templateContent);

            // 获取当前已有的结构项数量（排除隐藏模板）
            const existingItemsCount = container.find('.cloned-struct-item').length;
            // 更新新结构项中的 name 属性值
            newStructItem.find('input[name="names[0]"]').attr('name', `names[${existingItemsCount}]`);
            newStructItem.find('input[name="nameEns[0]"]').attr('name', `nameEns[${existingItemsCount}]`);
            newStructItem.find('select[name="typeId[0]"]').attr('name', `typeId[${existingItemsCount}]`);
            newStructItem.find('input[name="sorts[0]"]').attr('name', `sorts[${existingItemsCount}]`);

            // 为新克隆的删除按钮绑定事件
            newStructItem.find('button[lay-event="remove"]').off('click').on('click', function () {
                $(this).closest('.cloned-struct-item').remove(); // 删除当前结构项
                if (container.find('.cloned-struct-item').length === 0) {
                    // 如果所有结构项都被删除，重新添加一个隐藏模板
                    container.append($('#structTemplate').clone(true).addClass('hidden-template').hide());
                }
            });

            container.append(newStructItem); // 插入到外部盒子中
            // 在页面加载时加载初始的 select 选项
            $.ajax({
                url: baseURL + "cms/structParamType/list",
                type: 'get',
                success: function (res) {
                    let select = $('.struct-type-select');
                    select.empty(); // 清空现有的选项
                    res.data.forEach(function (option) {
                        select.append('<option value="' + option.typeId + '">' + option.name + '</option>');
                    });
                    form.render('select');
                }
            });
        });

        // 删除按钮点击事件
        container.on('click', 'button[lay-event="remove"]', function () {
            $(this).closest('.cloned-struct-item').remove(); // 删除当前结构项
            if (container.find('.cloned-struct-item').length === 0) {
                // 如果所有结构项都被删除，重新添加一个隐藏模板
                container.append($('#structTemplate').clone(true).addClass('hidden-template').hide());
            }
        });

        // 表单提交
        form.on('submit(struct-edit)', function (data) {
            let structItems = [];
            $('.struct .cloned-struct-item').each(function (index) {
                let item = {};
                // 动态获取每个结构项的表单数据
                item.name = $(this).find('input[name="names[' + index + ']"]').val(); // 获取中文名称
                item.nameEn = $(this).find('input[name="nameEns[' + index + ']"]').val(); // 获取英文名称
                item.typeId = $(this).find('select[name="typeId[' + index + ']"]').val(); // 获取文本类型
                item.sort = $(this).find('input[name="sorts[' + index + ']"]').val(); // 获取排序值
                structItems.push(item);
            });
            let formData = {
                structParamList: structItems,
                name: data.field.name,
                sort: data.field.sort,
                nameEn: data.field.nameEn,
                structId: parent.structId
            };
            $.ajax({
                url: baseURL + 'cms/struct/update',
                data: JSON.stringify(formData),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    if (result.code === 1000) {
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 2000
                        }, function () {
                            // 关闭当前层
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            // 刷新表格数据
                            parent.layui.table.reload("struct-table");
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                error: function () {
                    layer.msg('请求失败，请稍后重试。', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
            return false; // 阻止表单默认提交
        });
    });
</script>
</body>
</html>